//更新权限
function savePower() {
    var row = $('#treeGrid').treegrid('getSelected');

    if (row){
        let nodes = $('#tree').tree('getChecked');	// get checked nodes
        let ids = nodes.map(node=>node.id).join(",");
        let id = row.sysRoleId;
        if (id<0){
            return;
        }
        $.ajax({
            url:path_home+'/sysRole/updatePowers',
            data:{id: id,ids:ids},
            type:'post',
            dataType:'json',
            success:function(data){
                $.messager.show({
                    title:'提示',
                    msg:data.msg,
                    timeout:3000,
                    showType:'slide'
                });
                if(data.code>0){
                    //重新加载表单
                    // $('#tree').tree('reload');
                }
            }
        })
    }else{
        $.messager.alert("提示","请选择角色","info")
    }
}


//提交
function submitForm() {
    if (editingId!=undefined){
        $.messager.alert("提示","请先保存正在编辑的角色","info")
        return;
    }
    let treeGridList = $("#treeGrid").treegrid("getRoots");
    //处理集合
    treeGridList =  trans(treeGridList);

    $.ajax({
        url:path_home+'/sysRole/update',
        data:{sysRoleList: JSON.stringify(treeGridList)},
        type:'post',
        dataType:'json',
        success:function(data){
            $.messager.show({
                title:'提示',
                msg:data.msg,
                timeout:3000,
                showType:'slide'
            });
            if(data.code>0){
                //重新加载表单
                $('#treeGrid').treegrid('reload');
            }
        }
    })
}
//转换集合
function trans(list) {
    list = list.map(({sysRoleId,sysName,sysRoleRemake,sysRolePid,children,sysRoleLevel}) => ({sysRoleId,sysName,sysRoleRemake,sysRolePid,children,sysRoleLevel}));
    list.forEach(function(value, index, arr){
        if (value.children) {
            value.children = trans(value.children);
        }
    })
    return list;
}

var idGenerate =-1;//生成id
//添加子节点
function add(){
    if (editingId!=undefined){
        $.messager.alert("提示","请先保存正在编辑的角色","info")
        return;
    }
    var row = $('#treeGrid').treegrid('getSelected');
    $('#treeGrid').treegrid('append',{
        parent: row.sysRoleId,
        data: [{
            sysRoleId: --idGenerate,
            sysName: '新增节点',
            sysRolePid:row.sysRoleId
        }]
    });
    startEdit(idGenerate);
}
//添加根节点
function appendRoot(){
    if (editingId!=undefined){
        $.messager.alert("提示","请先保存正在编辑的角色","info")
        return;
    }
    $('#treeGrid').treegrid('append',{
        data: [{
            sysRoleId: --idGenerate,
            sysName: '新增节点',
            sysRolePid:0
        }]
    });
    startEdit(idGenerate);
}
//编辑刚新增的行
function startEdit(id){
    $('#treeGrid').treegrid('select', id);
    edit();
}
//删除行
function removeit(){
    $.messager.confirm('提示', '您确定要删除角色吗？', function(r){
        if (r){
            var row = $('#treeGrid').treegrid('getSelected');
            if (row.children!=null){
                $.messager.alert("提示","请先删除所有子角色","info")
                return;
            }
            if (row.sysRoleId>0){
                $.ajax({
                    url:path_home+'/sysRole/delete',
                    data:{id: row.sysRoleId},
                    type:'post',
                    dataType:'json',
                    success:function(data){
                        $.messager.show({
                            title:'提示',
                            msg:data.msg,
                            timeout:5000,
                            showType:'slide'
                        });
                        if(data.code>0){
                            //重新加载表单
                            $('#treeGrid').treegrid('reload');
                        }
                    }
                })
                return;
            }
            $('#treeGrid').treegrid('remove', row.sysRoleId);
            $.messager.show({
                title:'提示',
                msg:'删除成功',
                timeout:5000,
                showType:'slide'
            });
        }
    });
}

$(function () {
    $("#tree").tree(
        {
            url:path_home+'/sysPower/readPowerByRoleId?id=0',
            animate:true,
            checkbox:true,
            onDblClick : function(node) {
                // 展开/折叠
                if (node.state === 'open') {
                    $('#tree').tree('collapse', node.target);
                } else {
                    $('#tree').tree('expand', node.target);
                }
            }
        }
    );

    var levelData = [{"level":0,"name":"学生"},{"level":1,"name":"教职人员"}]

    $('#treeGrid').treegrid({
        url:path_home+'/sysRole/findAllRole',
        iconCls: 'icon-ok',
        animate: true,
        fitColumns:true,
        fit:true,
        method: 'get',
        idField:'sysRoleId',
        treeField:'sysName',
        columns:[[
            {field:'sysRoleId',title:'编号',width:80,align:'center',editable:true,checkbox:true},
            {field:'sysName',title:'角色名称',width:80,editor:'text'},
            {field:'sysRoleRemake',title:'备注',width:80,editor:'text',align:'center'},
            {field:'sysRoleLevel',title:'等级',width:80,align:'center',
                editor:{
                    type:'combobox',
                    options:{
                        valueField:'level',
                        textField:'level',
                        data:levelData,
                        required:true,
                        editable:false
                    }
                }
            },
            {field:'sysRoleTime',title:'创建时间',width:80,align:'center',
                formatter:function (value) {
                    return new Date(value).Format('yyyy-MM-dd hh:mm:ss')
                }
            },
        ]],
        //展开or收起
        onDblClickRow:function (row) {
            if (row.state==='open'){
                $("#treeGrid").treegrid("collapse",row.sysRoleId)
            }else{
                $("#treeGrid").treegrid("expand",row.sysRoleId)
            }
        },
        //右键菜单
        onContextMenu:function (e,row) {
            e.preventDefault();
            // select the node
            $('#treeGrid').treegrid('select', row.sysRoleId);
            // display context menu
            $('#mm').menu('show', {
                left: e.pageX,
                top: e.pageY
            });
        },
        //单击节点显示权限
        onSelect:function (row,checked) {
            $("#tree").tree({
                url:path_home+'/sysPower/readPowerByRoleId?id='+row.sysRoleId
            })
        },
        onBeginEdit:function (row) {
            let t = $("#treeGrid")
            let editor =t.treegrid("getEditor",{id:row.sysRoleId,field:"sysRoleLevel"})
            let parent = t.treegrid('getParent',row.sysRoleId);
            if (parent==null||parent.sysRoleLevel>0){
                editor.target.combobox({
                    data:[{"level":0,"name":"学生"},{"level":1,"name":"教职人员"}],
                })
                editor.target.combobox("select",row.sysRoleLevel)
            } else{
                editor.target.combobox({
                    data: [{"level":0,"name":"学生"}]
                })
                editor.target.combobox("select",row.sysRoleLevel)
            }
        }
    });
})

var editingId;//正在编辑的节点
function edit(){
    if (editingId != undefined){
        $('#treeGrid').treegrid('select', editingId);
        return;
    }
    let t = $('#treeGrid');
    let row = t.treegrid('getSelected');

    if (row){
        editingId = row.sysRoleId
        $('#treeGrid').treegrid('beginEdit', editingId);

    }else{
        $.messager.alert("提示","请选择角色","info")
    }
}
function save(){
    if (editingId != undefined){
        var t = $('#treeGrid');
        var row = t.treegrid('getSelected');
        t.treegrid('endEdit', editingId);
        editingId = undefined;
    }
}
function cancel(){
    if (editingId != undefined){
        $('#treeGrid').treegrid('cancelEdit', editingId);
        editingId = undefined;
    }
}

